<?php

namespace app\web\home;

use app\web\model\Technician as myModel;
use app\web\model\TechnicianBalance;
use app\web\model\Scheduling;
use app\web\model\CouponType;
use app\web\model\Shop;
use app\web\model\Follow;
use app\web\model\Job;
use app\web\model\Tags;
use app\web\model\User;
use app\web\model\Order;
use app\web\model\Config;
use app\web\model\ProjectTechnician;
use app\web\model\TechnicianQualifications;
use app\web\model\TechnicianCheck;
use think\Db;
use think\facade\Cache;
use app\lib\model\Tool;
use app\lib\model\Price;

class Technician extends Base 
{
    protected $middleware = [ 
        'TechnicianMiddleware' => ['only'      => ['info']],
    ];
    /**
     * [addTop description]
     * @param [type] $code [description]
     */
    public function addTop($code)
    {
        $topuser = User::get((int)$code);
        if(!$topuser) return show(400,'邀请码错误');
        if($topuser->id == $this->uid){
            return show(400,'不可绑定自己成为上级');
        }
        $user = User::get($this->uid);
        if($user->p_id > 0) return show(400,'已绑定,不可重复绑定');
        $user->p_id = (int)$code;
        $user->save();
        return show(200,'绑定成功');
    }

    /**
     * 获取承诺函
     * [getPromise description]
     * @return [type] [description]
     */
    public function getPromise()
    {
        return show(200,'承诺函',Config::getConfig($this->appkey == 1 ? 'promise_path' : 'shop_promise_path'));
    }
    /** 
     * 技师列表
     * [getAll description]
     * @return [type] [description]
     */
    public function getAll()
    {
        $city = input('city');
        $params = input('post.');
        
        $where[] = ['a.city','like','%'.$city.'%'];
        $where[] = ['a.check_status','=',1];
        $where[] = ['a.is_sale','=',1];
        $where[] = ['a.is_sale1','=',1];
        $where[] = ['a.is_online','=',1];
        $where[] = ['a.is_period','=',0];
        $where[] = ['a.is_project','=',1];
        if(!empty($params['category_id'])){
            $where[] = ['a.id','in',ProjectTechnician::getTidByCategoryID($params['category_id'])];
        }
        if(!empty($params['shop_id']) && $params['shop_id'] > 0){
            $where[] = ['a.shop_id','=',$params['shop_id']];
        }
        if(isset($params['gender'])){
            $where[] = ['a.gender','=',$params['gender']];
        }
        if(!empty($params['score'])){
            $where[] = ['a.score','>=',$params['score']];
        }
        if(!empty($params['qualifications'])){
            // $ids = TechnicianQualifications::where(['job_id'=>$params['qualifications'],'status'=>1])->column('technician_id');
            // if(!$ids) return show(200,'技师列表',[]);
            $where[] = ['a.job_ids','like','%'.$params['qualifications'].'%']; 
        }
        if(!empty($params['key'])){
            $where[] = ['a.nickName','like','%'.$params['key'].'%'];
        }

        if(isset($params['tags'])){ // 0优选推荐 1今日推荐 2近期成交
            switch($params['tags']){
                case '0':
                    $where[] = ['is_recommend','=',1];
                    break;
                case '1':
                    $order = 'a.sign_time desc';
                    break;
                case '2':
                    //近期成交
                    $deal_dat = Config::getConfig('deal_dat');
                    $deal_dat = strtotime(date("Y-m-d",strtotime(-$deal_dat.' day')));
                    $t_ids = Order::where([['create_time','>',$deal_dat]])->field('sum(number) as number,technician_id')->group('technician_id')->all()->toArray();
                    if(!$t_ids) return show(200,'技师列表',[]);
                    $t_ids = array_field_sort($t_ids,'number','desc',true);
                    $t_ids = array_column($t_ids, 'technician_id');
                    $where[] = ['a.id','in',$t_ids];
                    break;
            }
        }
        $order = 'distance,a.order_number desc,a.score desc,a.create_time desc';
        if(isset($params['order'])){
            switch($params['order']){
                case '0':
                    $order = 'a.order_number desc,a.score desc,a.create_time desc';
                    break;
                case '1':
                    $order = 'a.order_number desc';
                    break;
                case '2':
                    //距离最近
                    $order = 'distance';   
                    break;
                case '3':
                    $order = 'a.create_time desc';
                    break;
                case '4':
                    $order = 'a.score desc,a.order_number desc';
                    break;
                default:
                    $order = 'a.order_number,a.score desc';  
            }
        }
        $user = User::get($this->uid);
        $product = Tool::getProduct($user->longitude,$user->latitude);
        $sql = myModel::alias('a')
                        ->where($where)
                        ->field('a.id,a.nickName,a.shop_mobile,a.score,a.order_number,a.shop_id,a.avatarUrl,a.avatar_similarity,a.real_status,a.traffic_id,a.is_recommend,a.product,a.qualifications_status,a.loc_longitude as longitude,a.loc_latitude as latitude,a.tags_ids,abs(a.product-'.($product/10000000).') as distance,a.create_time')
                        ->select(false);

        $list = Db::table('('.$sql.')')->alias('a')
                    ->leftjoin('shop b','b.id=a.shop_id')
                    ->leftjoin('traffic c','c.id=a.traffic_id')
                    ->field('a.*,ifnull(b.shop_name,"") as shop_name,ifnull(c.traffic_name,"") as traffic_name')
                    ->order($order)
                    ->paginate()->toArray();
        $data = $list['data'];
        $time = $this->request->time();
        $time_date = strtotime(date('Y-m-d'));
        foreach ($data as $key => $value) {
            $data[$key]['avatar_authentication'] = $value['avatar_similarity'] < 70 ? 0 : 1;   //头像是否认证
            $data[$key]['is_mobile'] = $data[$key]['shop_mobile'] ? 1 : 0;
            $coupon_type = CouponType::where(['coupon_type'=>2,'technician_id'=>$value['id'],'status'=>1])->field('money,full_money')->find();
            $data[$key]['coupon_money'] = $coupon_type['money'] ?? 0;
            $data[$key]['full_money'] = $coupon_type['full_money'] ?? 0;
            $data[$key]['distance'] = Tool::getDistance($user['longitude'],$user['latitude'],$value['longitude'],$value['latitude']);
            $data[$key]['tags'] = $value['tags_ids'] ? Tags::where('id','in',$value['tags_ids'])->column('tags_name') : [];
            $data[$key]['qualifications'] = TechnicianQualifications::alias('a')
                                            ->where(['a.technician_id'=>$value['id'],'a.status'=>1])
                                            ->leftjoin('job b','b.id=a.job_id')
                                            ->column('b.job_name');
            
            $scheduling = Scheduling::where([['technician_id','=',$value['id']],['start_time','<',$time],['start_time','>',$time-1800],['status','=',2]])->find();
            if($scheduling){  
                $data[$key]['scheduling_status'] = 2;  //服务中
            }else{
                $scheduling = Scheduling::where([['technician_id','=',$value['id']],['start_time','>',$time],['status','=',0]])->find();
                $data[$key]['scheduling_status'] = $scheduling ? 0 : 1;
            }
            unset($data[$key]['product']);
            unset($data[$key]['longitude']);
            unset($data[$key]['latitude']);
            unset($data[$key]['shop_mobile']);
            unset($data[$key]['shop_id']);
            unset($data[$key]['avatar_similarity']);
            unset($data[$key]['tags_ids']);
            unset($data[$key]['traffic_id']);
        }
        $list['data'] = $data;       
        // Cache::set($md5,$list,180);
        return show(200,'技师列表',$list);
    }
    
    // /**
    //  * 首页列表
    //  * [getList description]
    //  * @return [type] [description]
    //  */
    // public function getList()
    // {
    //     $order = input('order',0);
    //     // $city = User::where('id',$this->uid)->value('city');
    //     $city = input('city','');
    //     $where[] = ['a.city','like','%'.$city.'%'];
    //     $where[] = ['a.is_online','=',1];
    //     $where[] = ['a.is_sale','=',1];
    //     $where[] = ['a.is_sale1','=',1];
    //     $where[] = ['a.check_status','=',1];
    //     $where[] = ['a.is_period','=',0];
    //     $where[] = ['a.is_project','=',1];
    //     if(!empty($params['category_id'])){
    //         $where[] = ['a.id','in',ProjectTechnician::getTidByCategoryID($params['category_id'])];
    //     }
    //     $product = Tool::getProduct(input('longitude'),input('latitude'));
    //     $list = [];
    //     if($order == 0){  //红牌推荐 
    //         $where[] = ['is_recommend','=',1];
    //         $sql = myModel::alias('a')
    //                     ->where($where)
    //                     ->field('a.id,a.nickName,a.shop_mobile,a.shop_id,a.avatarUrl,a.avatar_similarity,a.real_status,a.traffic_id,a.is_recommend,a.product,abs(a.product-'.($product/10000000).') as distance')
    //                     ->select(false);
    //         $list = Db::table('('.$sql.')')->alias('a')
    //                     ->leftjoin('shop b','b.id=a.shop_id')
    //                     ->leftjoin('traffic c','c.id=a.traffic_id')
    //                     ->field('a.*,ifnull(b.shop_name,"") as shop_name,ifnull(c.traffic_name,"") as traffic_name')
    //                     ->order('distance')
    //                     ->paginate()->each(function($item,$key){
    //                         $item['avatar_authentication'] = $item['avatar_similarity'] < 70 ? 0 : 1;   //头像是否认证
    //                         $item['is_mobile'] = $item['shop_mobile'] ? 1 : 0;
    //                         $coupon_type = CouponType::where(['coupon_type'=>2,'technician_id'=>$item['id'],'status'=>1])->field('money,full_money')->find();
    //                         $item['coupon_money'] = $coupon_type['money'] ?? 0;
    //                         $item['full_money'] = $coupon_type['full_money'] ?? 0;
    //                         return $item;
    //                     });
    //     }elseif($order == 1){ //今日推荐按打卡时间倒叙
    //         $list = myModel::alias('a')
    //                         ->leftjoin('shop b','b.id=a.shop_id')
    //                         ->field('a.id,a.nickName,a.shop_mobile,a.shop_id,a.avatarUrl,a.avatar_similarity,a.real_status,a.traffic_id,a.is_recommend,ifnull(b.shop_name,"") as shop_name,ifnull(c.traffic_name,"") as traffic_name')
    //                         ->leftjoin('traffic c','c.id=a.traffic_id')
    //                         ->where($where)
    //                         ->order('a.sign_time desc')
    //                         ->paginate()->each(function($item,$key){
    //                             $item['avatar_authentication'] = $item['avatar_similarity'] < 70 ? 0 : 1;   //头像是否认证
    //                             $item['is_mobile'] = $item['shop_mobile'] ? 1 : 0;
    //                             $coupon_type = CouponType::where(['coupon_type'=>2,'technician_id'=>$item['id'],'status'=>1])->field('money,full_money')->find();
    //                             $item['coupon_money'] = $coupon_type['money'] ?? 0;
    //                             $item['full_money'] = $coupon_type['full_money'] ?? 0;
    //                         });
    //     }elseif($order == 2){   //近期成交排序 按照后台设置多少天内成交单数来排序
    //         $deal_dat = Config::getConfig('deal_dat');
    //         $deal_dat = strtotime(date("Y-m-d",strtotime(-$deal_dat.' day')));
    //         $where[] = ['d.create_time','>',$deal_dat];
    //         $list = myModel::alias('a')
    //                         ->leftjoin('shop b','b.id=a.shop_id')
    //                         ->leftjoin('order d','d.technician_id=a.id')
    //                         ->leftjoin('traffic c','c.id=a.traffic_id')
    //                         ->field('a.id,a.nickName,a.shop_mobile,a.shop_id,a.avatarUrl,a.avatar_similarity,a.real_status,a.traffic_id,a.is_recommend,ifnull(b.shop_name,"") as shop_name,ifnull(c.traffic_name,"") as traffic_name,sum(d.number) as number')
    //                         ->where($where)
    //                         ->group('d.technician_id')
    //                         ->order('number desc')
    //                         ->paginate()->each(function($item,$key){
    //                             $item['avatar_authentication'] = $item['avatar_similarity'] < 70 ? 0 : 1;   //头像是否认证
    //                             $item['is_mobile'] = $item['shop_mobile'] ? 1 : 0;
    //                             $coupon_type = CouponType::where(['coupon_type'=>2,'technician_id'=>$item['id'],'status'=>1])->field('money,full_money')->find();
    //                             $item['coupon_money'] = $coupon_type['money'] ?? 0;
    //                             $item['full_money'] = $coupon_type['full_money'] ?? 0;
    //                         });

    //     }
    //     return show(200,'技师列表',$list);
    // }

    /**
     * 用户端技师详情
     * [find description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function find($id){
        $user = User::get($this->uid);
        $info = myModel::alias('a')
                        ->where('a.id',$id)
                        ->leftjoin('shop b','b.id=a.shop_id')
                        ->leftjoin('traffic c','c.id=a.traffic_id')
                        ->field('a.id,a.nickName,a.avatarUrl,a.job_ids,a.avatar_similarity,a.score,a.follow_number,a.order_number,a.gender,a.age,a.loc_longitude as longitude,a.loc_latitude as latitude,a.qualifications_status,a.technician_introduction,if(a.album_status=2,a.album,"") as album,a.real_name,a.real_status,a.traffic_id,a.shop_mobile,a.shop_id,ifnull(b.shop_name,"") as shop_name,ifnull(c.traffic_name,"") as traffic_name,a.tags_ids,a.works_status,a.works,a.sign_time,a.balance')
                        ->find()->toArray();

        $info['sign_time'] = $info['sign_time'] ? date('Y-m-d') : '';
        $info['avatar_authentication'] = $info['avatar_similarity'] < 65 ? 0 : 1;
        $info['is_mobile'] = $info['shop_mobile'] ? 1 : 0;
        $info['is_follow'] = Follow::isFollow($info['id'],$this->uid);

        $info['qualifications'] = Job::where('id','in',$info['job_ids'])->column('job_name');
         // TechnicianQualifications::alias('a')
         //                                    ->where(['a.technician_id'=>$info['id'],'a.status'=>1])
         //                                    ->leftjoin('job b','b.id=a.job_id')
         //                                    ->column('b.job_name');
        $info['distance'] = Tool::getDistance($user['longitude'],$user['latitude'],$info['longitude'],$info['latitude']);
        $info['tags'] = $info['tags_ids'] ? Tags::where('id','in',$info['tags_ids'])->column('tags_name') : [];
        $info['works'] = $info['works_status'] == 2 ? $info['works'] : [];
        return show(200,'技师详情',$info);
    }
    /**
     * 技师详情页推荐技师
     * [getRecTechnician description]
     * @param  [type] $shop_id [description]
     * @return [type]          [description]
     */
    public function getRecTechnician($shop_id)
    {
        $user = User::get($this->uid);
        $where[] = ['a.shop_id','=',$shop_id];
        $where[] = ['a.is_online','=',1];
        $where[] = ['a.is_sale','=',1];
        $where[] = ['a.is_sale1','=',1];
        $where[] = ['a.check_status','=',1];
        $where[] = ['a.is_period','=',0];
        $where[] = ['a.is_project','=',1];
        $where[] = ['a.is_recommend','=',1];
        $list = myModel::alias('a')->where($where)
                    ->field('a.id,a.nickName,a.shop_mobile,a.avatarUrl,a.score,a.avatar_similarity,a.tags_ids,a.shop_id,a.real_status,b.shop_name,a.order_number,a.loc_longitude as longitude,a.loc_latitude as latitude,"'.$user['longitude'].'" as my_longitude,"'.$user['latitude'].'" as my_latitude')
                    ->leftjoin('shop b','b.id=a.shop_id')
                    ->paginate()->each(function($item,$k){
                        $item['avatar_authentication'] = $item['avatar_similarity'] < 70 ? 0 : 1;   //头像是否认证
                        $item['is_mobile'] = $item['shop_mobile'] ? 1 : 0;
                        $item['distance'] = Tool::getDistance($item['my_longitude'],$item['my_latitude'],$item['longitude'],$item['latitude']);
                        $item['tags'] = $item['tags_ids'] ? Tags::where('id','in',$item['tags_ids'])->column('tags_name') : [];
                        $item['qualifications'] = TechnicianQualifications::alias('a')
                                            ->where(['a.technician_id'=>$item['id'],'a.status'=>1])
                                            ->leftjoin('job b','b.id=a.job_id')
                                            ->column('b.job_name');
                    });
        return show(200,'推荐技师',$list);
    }
    /************************************技师端
    /**
     * 提交技师信息
     * [add description]
     */
    public function add(){
        $post = input('post.');
        $this->validate($post,'Technician');
        if($post['mobile_code'] != 123456 && $post['mobile_code'] != Cache::get($post['shop_mobile'])){
            return show(400,'短信验证码错误');
        }
        $job_ids = is_array($post['job_ids']) ? implode(',', $post['job_ids']) : $post['job_ids'];
        if(!empty($post['shop_code'])){
            if(Shop::where(['id'=>$post['shop_code']])->count() == 0) return show(400,'商戶号码错误');
        }
        // $qualifications = $post['qualifications'] ?? [];
        $technician = myModel::where(['user_id'=>$this->uid])->find();
        Db::startTrans();
        $post['is_sub'] = 1;
        $post['sub_time'] = $this->request->time();
        $post['check_status'] = 0;
        $post['check_reason'] = '';
        $post['check_time'] = null;
        $post['check_uid'] = 0;
        $post['is_sale'] = 1;
        $location = Tool::coordinateToAddress($post['loc_latitude'],$post['loc_longitude']);
        if($location){
            $post['province'] = $location['address_component']['province'];
            $post['city'] = $location['address_component']['city'];
            $post['area'] = $location['address_component']['district'];   
        }
        $post['product'] = Tool::getProduct($post['loc_longitude'],$post['loc_latitude']);
        $res = $technician->save($post);
        if(!$res) return show(400,'提交失败');
        
        $t_check = TechnicianCheck::where(['technician_id'=>$technician->id,'field_key'=>'job_ids'])->find();
        if($t_check){
            $t_check->check_time = null;
            $t_check->field_val = $job_ids;
            $t_check->status = 0;
            $t_check->create_time = time();
            $t_check->update_time = time();
            $t_check->check_before = $technician->job_ids;
            $res = $t_check->save();
            if(!$res){
                Db::rollback();
                return show(400,'提交失败');
            }
        }else{
            $res = TechnicianCheck::create([
                'technician_id' => $technician->id,
                'field_key' => 'job_ids',
                'field_val' => $job_ids,
                'check_before' => $technician->job_ids
            ]);
            if($res->isEmpty()) {
                Db::rollback();
            return show(400,'提交失败');
            }
        }
        // if($qualifications){
        //     $res = TechnicianQualifications::add($qualifications,$technician->id);
        //     if($res !== true){
        //         Db::rollback();
        //         return show(400,$res);
        //     }
        // }
        Db::commit();
        return show(200,'提交成功,等待审核');
    }
    public function getLocation($t_id){
        $info = myModel::field('id,loc_longitude,loc_latitude')->get($t_id);
        return show(200,'技师入驻位置',$info);
    }
    /**
     * 实时定位
     * [addLocation description]
     */
    public function addLocation()
    {
        $post = input('post.');
        $post['longitude'] = $post['longitude'] ?? 0;
        $post['latitude'] = $post['latitude'] ?? 0;
        $post['product'] = Tool::getProduct($post['longitude'],$post['latitude']);
        $post['sign_time'] = time();
        $info = myModel::where(['user_id'=>$this->uid])->find();
        //判断是否同一城市,上线下线
        $res = Tool::coordinateToAddress($post['latitude'],$post['longitude']);
        $city = ($info['city'] == '市辖区' || $info['city'] == '县') ? $ifno['province'] : $info['city'];
        if(!$res || $city != $res['address_component']['city']){
            $info->is_online = 0;
        }else{
            $info->is_online = 1;
        }
        if($info->save($post)) return show(200,'提交成功');
        return show(400,'定位失败');

    }
    //修改技师资料
    public function edit($t_id = 0)
    {
        $post = input('post.');
        if(isset($post['mobile_code']) && $post['mobile_code'] != 123456 && $post['mobile_code'] != Cache::get($post['shop_mobile'])){
            return show(400,'短信验证码错误');
        }
        if($this->appkey == 1){
            $technician = myModel::where(['user_id'=>$this->uid])->find();
        }else{
            $technician = myModel::get($t_id);
        }

        if(isset($post['shop_code']) && $technician->shop_id > 0){
            return show(400,'您已绑定商家,不可重复绑定商家');
        }
        $post['is_sale1'] = 0;
        if($technician->save($post)) return show(200,'提交成功');
        return show(400,'提交失败');
    }
    /**
     * 修改需要审核的字段  ['avatarUrl','avatar_similarity','real_name','id_card','technician_introduction']
     * [editField description]
     * @return [type] [description]
     */
    public function editField()
    {
        $post = input('post.');
        $technician = myModel::where(['user_id'=>$this->uid])->find();

        $arr = [];
        $t_check = TechnicianCheck::where(['technician_id'=>$technician->id])->all()->toArray();
        $t_check = array_column($t_check,null, 'field_key');
        $time = time();
        $f['create_time'] = $time;
        $f['update_time'] = $time;
        $f['status'] = 0;
        $f['check_time'] = null;
        $f['no_check_desc'] = '';
        $f['reason_id'] = 0;
        $f['technician_id'] = $technician->id;
        foreach ($post as $key => $value) {
            if($value){
                $field = $f;
                $field['field_key'] = $key;
                $field['field_val'] = $value;
                $field['check_before'] = $technician->$key;
                if(isset($t_check[$key])){
                    $field['id'] = $t_check[$key]['id'];
                }
                $arr[] = $field;
            }
        }
        $model = new TechnicianCheck();
        $res = $model->saveAll($arr);
        if($res) {
            $technician->is_sale1 = 0;
            $technician->save();
           return show(200,'提交成功'); 
        }
        return show(400,'提交失败');
    }
    /**
     * 我的认证资料
     * [getQualifications description]
     * @return [type] [description]
     */
    public function getQualifications()
    {
        $t_id = $this->getCurrentId();
        $list = TechnicianQualifications::alias('a')
                            ->where(['a.technician_id'=>$t_id])
                            ->leftjoin('job b','b.id=a.job_id')
                            ->field('a.id,a.job_id,a.qualifications_image,b.job_name,a.status,a.check_reason,a.check_time,a.create_time')
                            ->select();
        return show(200,'我的认证资料',$list);
    }
    /**
     * 添加资质认证
     * [addQualifications description]
     */
    public function addQualifications()
    {
        $post = input('post.');
        if(empty($post['qualifications'])) return show(400,'请上传资质证书');
        $t_id = $this->getCurrentId();
        $res = TechnicianQualifications::add($post['qualifications'],$t_id);
        if($res === true) {
            $technician = myModel::get($t_id);
            $technician->qualifications_status = 0;
            $technician->is_sale1 = 0;
            $technician->save();
            return show(200,'添加成功');
        }
        return show(400,$res);
    }
    /**
     * 重新提交资质认证
     * [editQualifications description]
     * @return [type] [description]
     */
    public function editQualifications()
    {
        $post = input('post.');
        $info = TechnicianQualifications::get($post['id']);
        $info->status = 0;
        $info->check_reason = '';
        $info->check_time = null;
        $info->check_uid = 0;
        $res = $info->save($post);
        if($res) {
            $technician = myModel::get($this->getCurrentId());
            $technician->qualifications_status = 0;
            $technician->is_sale1 = 0;
            $technician->save();
            return show(200,'提交成功,等待审核');
        }
        return show(400,'提交失败');
    }
    /**
     * 技师详情
     * [info description]
     * @return [type] [description]
     */
    public function info()
    {
        $info = myModel::alias('a')
                        ->where('a.user_id',$this->uid)
                        ->leftjoin('shop c','c.id=a.shop_id')
                        ->leftjoin('experience b','b.id=a.experience_id')
                        ->field('a.id,a.nickName,a.job_ids,a.promise_path,a.avatarUrl,a.avatar_similarity,a.is_sub,a.sub_time,a.is_online
                            ,a.is_sale,a.is_sale1,a.check_status,a.check_time,a.check_reason,a.gender,a.age,a.wx_code,a.shop_mobile,a.traffic_id,a.province,ifnull(c.shop_name,"") as shop_name,ifnull(c.avatarUrl,"") as shop_avatarUrl,a.shop_id,a.city,a.area,a.address,a.experience_id,b.experience_name,a.real_name,a.id_card,a.technician_introduction,a.id_card,a.real_name,a.shop_check_time,a.service_area,a.is_period')
                        ->find();
        $info['is_online'] = ($info['is_sale'] == 1 && $info['is_sale1']) == 1 ? 1 : 0;
        $technician_check = TechnicianCheck::where(['technician_id'=>$info['id'],'field_key'=>'technician_introduction'])->find();
        $info['technician_introduction_status'] = $technician_check ? $technician_check['status'] : -1;
        $info['job_ids'] = Job::where('id','in',$info->job_ids)->field('id as job_id,job_name')->select();
        $t = Price::pricecalc(86400,'*',Config::getConfig('deal_dat'),0);
        $a = Order::where(['technician_id'=>$info['id']])->where([['status','in','2,3,4'],['create_time','>',$t]])->count();
        $b = Order::where(['technician_id'=>$info['id']])->where([['create_time','>',$t]])->count();
        $info['receiving_order_rate'] =  $b == 0 ? 0 : floatval(Price::pricecalc(Price::pricecalc($a,'/',$b),'*',100,2));
        $c = Order::where(['technician_id'=>$info['id']])->where([['status','in','4']])->count();
        $d = Order::where(['technician_id'=>$info['id']])->count();
        $info['deal_order_rate'] =  $d == 0 ? 0 : floatval(Price::pricecalc(Price::pricecalc($c,'/',$d),'*',100,2));
        if($this->appkey == 1 && $info->is_period == 1){
            return show(605,'已到期');
        }
        return show(200,'技师信息',$info);
    }

    /**
     * 技术认证信息
     * [authentication description]
     * @return [type] [description]
     */
    public function authentication()
    {
        $info = myModel::getAuthentication($this->uid);

        return show(200,'技师认证信息',$info);
    }
    public function getFieldVal()
    {
        $key = input('key');
        $arr = ['id_card','avatarUrl','promise_path','job_ids'];
        $t_id = $this->getCurrentId();
        $info = TechnicianCheck::where(['technician_id'=>$t_id,'field_key'=>$key])
                            ->field('field_key,field_val,status,check_time,create_time as sub_time,no_check_desc')
                            ->find();
        $info = $info ?? [];
        if($info){
            $info['check_time'] = date('Y-m-d H',$info['check_time']);
            $info['sub_time'] = date('Y-m-d H',$info['sub_time']);
            if($key == 'id_card') $info['real_name'] = TechnicianCheck::where(['technician_id'=>$t_id,'field_key'=>'real_name'])->value('field_val');
            if($key == 'avatarUrl') $info['avatar_similarity'] = TechnicianCheck::where(['technician_id'=>$t_id,'field_key'=>'avatar_similarity'])->value('field_val');
            if($key == 'job_ids'){
                $info['field_val'] = Job::where('id','in',$info['field_val'])->field('id,job_name')->all()->toArray();
            }
        }
        return show(200,'审核数据',$info ?? []);
    }
    public function getCheckMessage()
    {
        return show(200,'技师首页公告信息',myModel::getCheckMessage($this->getCurrentId()));
    }
    /**
     * 获取我的相册
     * [getAlbum description]
     * @return [type] [description]
     */
    public function getAlbum()
    {
        $info = myModel::where('user_id',$this->uid)
                    ->field('album,album_sub_time,album_status,album_reason,album_check_time')
                    ->find();
        return show(200,'我的相册',$info);
    }
    /**
     * 上传相册
     * [addAlbum description]
     */
    public function addAlbum()
    {
        $post = input('post.');
        if(empty($post['album'])) return show(400,'请上传图片');
        $info = myModel::where(['user_id'=>$this->uid])->find();
        $info->album = $post['album'];
        $info->album_sub_time = time();
        $info->album_status = 1;
        $info->is_sale1 = 0;
        if($info->save()) return show(200,'提交成功');
        return show(400,'提交失败');
    }
    /**
     * 我的作品相册
     * [getWorks description]
     * @return [type] [description]
     */
    public function getWorks()
    {
        $info = myModel::where('user_id',$this->uid)
                    ->field('works,works_sub_time,works_status,works_reason,works_check_time')
                    ->find();
        return show(200,'我的作品相册',$info);
    }
    public function addWorks()
    {
        $post = input('post.');
        if(empty($post['works'])) return show(400,'请上传图片');
        $info = myModel::where(['user_id'=>$this->uid])->find();
        $info->works = $post['works'];
        $info->works_sub_time = time();
        $info->works_status = 1;
        $info->is_sale1 = 0;
        if($info->save()) return show(200,'提交成功');
        return show(400,'提交失败');
    }
    /**
     * 加入商户
     * [addShop description]
     * @param [type] $code [description]
     */
    public function addShop($code)
    {
        $shop = Shop::get($code);
        if(!$shop) return show(400,'请输入正确的邀请码');
        $info = myModel::where(['user_id'=>$this->uid])->find();
        if($info['shop_id'] > 0) return show(400,'已加入商户,不可重复加入');
        $info->shop_code = (int)$code;
        $info->shop_check_status = 0;
        if($info->save()) return show(200,'提交成功');
        return show(400,'提交失败');
    }
    /**
     * 解除商家綁定
     * [unbundling description]
     * @return [type] [description]
     */
    public function unbundling()
    {
        $info = myModel::where(['user_id'=>$this->uid])->find();
        $shop_id = $info->shop_id;
        if($shop_id == 0) return show(200,'解除綁定成功');
        $info->shop_id = 0;
        $info->shop_code = 0;
        $info->shop_check_status = 0;
        $info->shop_check_time = 0;
        $info->save();
        ProjectTechnician::where(['shop_id'=>$shop_id,'technician_id'=>$this->getCurrentId()])->update(['delete_time'=>time()]);
        $data = ProjectTechnician::where(['shop_id'=>$shop_id])->find();
        $shop = Shop::get($shop_id);
        $shop->t_number = $shop->t_number-1;
        if(!$data) $shop->is_ids = 0;
        $shop->save();
        return show(200,'解除綁定成功');
    }
    
    /**
     * 设置N公里免费
     * [addTraffic description]
     * @param [type]  $id   [description]
     * @param integer $t_id [description]
     */
    public function addTraffic($id,$t_id = 0)
    {
        if($this->appkey == 2 && $this->auth_status == 2) return show(400,'无操作权限');
        $t_id = $this->appkey == 1 ? $this->getCurrentId() : $t_id;
        $info = myModel::get($t_id);
        $info->traffic_id = $id;
        $info->save();
        return show(200,'修改成功');
    }
    /**
     * 设置服务区域
     * [serviceArea description]
     * @param  [type]  $number [description]
     * @param  integer $t_id   [description]
     * @return [type]          [description]
     */
    public function serviceArea($number,$t_id = 0)
    {
        $t_id = $this->appkey == 1 ? $this->getCurrentId() : $t_id;
        $info = myModel::get($t_id);
        $info->service_area = (int)$number;
        $info->save();
        return show(200,'修改成功');
    }
    /**
     * 上传承诺函
     * [addPromisePath description]
     */
    // public function addPromisePath()
    // {
    //     $res = myModel::where(['user_id'=>$this->uid])->update(['promise_path'=>input('promise_path')]);

    //     return show(200,'上传成功');
    // }
    /**
     * 技师上线/下线
     * [online description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function online($id)
    {
        if($this->auth_status == 2) return show(400,'无操作权限');
        $data = myModel::get($id);
        $data->is_sale = $data->is_sale == 1 ? 0 : 1;
        if($data->save()) return show(200,'操作成功');
        return show(400,'操作失败');
    }

    /**
     * 店铺审核技师
     * [checkTechnician description]
     * @return [type] [description]
     */
    public function checkTechnician()
    {
        if($this->auth_status == 2) return show(400,'无操作权限');
        $post = input('post.');
        $source = input('source',0);
        $technician = myModel::get($post['id']);
        if($technician->shop_code != $this->getCurrentId()){
            return show(400,'审核失败');
        }
        $technician->shop_check_status = $post['shop_check_status'];
        $technician->shop_id = $technician->shop_code;
        $technician->shop_check_time = time();
        if($post['shop_check_status'] == 1){
            $technician->source = $source;
        }
        if($technician->save()){
            Shop::where('id',$technician->shop_id)->setInc('t_number');
            return show(200,'审核成功');
        } 
        return show(400,'审核失败');
    }


    /**
     * 技师财务报表
     * [profit description]
     * @param  integer $status [description]
     * @return [type]          [description]
     */
    public function profit($status = 0)
    {
        $t_id = $this->getCurrentId();
        $group = '"%Y-%m-%d"';
        if($status == 1){
            $group = '"%Y-%m"';
        }elseif($status == 2) {
            $group = '"%Y"';
        }
        $data = TechnicianBalance::where([['t_id','=',$t_id],['balance_type','in','1,2'],['status','=',1]])
                                ->field('count(distinct order_id) as number,sum(change_balance) as money,FROM_UNIXTIME(create_time,'.$group.') as create_date')
                                ->order('id desc')
                                ->group('FROM_UNIXTIME(create_time,'.$group.')')
                                ->paginate();
        
        return show(200,'技师报表',$data);
    }
    /**
     * 我的财务
     * [finance description]
     * @return [type] [description]
     */
    public function finance($t_id = 0){
        if($this->appkey == 1){
            $technician = myModel::get($this->getCurrentId());
            $arr = [];
            $arr['is_shop'] = $technician['shop_id'] == 0 ? 0 : 1;
        }else{
            $technician = myModel::get($t_id);
            $arr = [];
            $arr['is_shop'] = $technician['shop_id'] == 0 ? 0 : 1;
        }
        
        if($arr['is_shop'] == 1){   //绑定商家的技师  
            //累计收入
            $arr['cumulative_money'] = TechnicianBalance::where(['t_id'=>$technician['id']])->value('sum(change_balance)');
            //累计已发放
            $arr['grant_money'] = 0;
        }else{     //个人技师   
            //已提现金额
            $arr['cash_withdrawn'] = TechnicianBalance::where(['t_id'=>$technician['id'],'balance_type'=>3,'status'=>1])->value('ifnull(sum(abs(change_balance)),0)');
            $arr['withdrawn_money'] = Price::pricecalc($technician->balance,'-',TechnicianBalance::where(['t_id'=>$technician['id'],'balance_type'=>3,'status'=>0])->value('ifnull(sum(abs(change_balance)),0)'));
        }
        return show(200,'余额',$arr);
      
    }
    /**
     * 技师余额流水
     * [balance description]
     * @param  [type] $status [description]
     * @return [type]         [description]
     */
    public function balance($status = 0,$t_id = 0)
    {
        $t_id = $t_id == 0 ? $this->getCurrentId() : $t_id;
        $where[] = ['a.t_id','=',$t_id];
        $field = 'a.id,a.change_balance,a.after_balance,a.order_id,a.update_time as create_time,a.notes,a.status,b.nickName,b.avatarUrl';
        if($status == 1){
            $where[] = ['a.balance_type','=',3];
        }elseif($status == 2){
            $where[] = ['a.balance_type','=',4];
        }
        $list = TechnicianBalance::alias('a')->where($where)->leftjoin('technician b','b.id=a.t_id')
                                    ->field($field)
                                    ->order('id desc')
                                    ->paginate();
        return show(200,'余额流水',$list);
    }
    /**
     * 技师端提现申请
     * [withdrawal description]
     * @param  [type] $money [description]
     * @return [type]        [description]
     */
    public function withdrawal($money)
    {
        $t_id = $this->getCurrentId();
        if(bccomp(0.01,$money,2) == 1) return show(400,'提现金额必须大于0');
        $technician = myModel::get($t_id);
        if($technician['shop_id'] > 0) return show(400,'已绑定商家不可提现');
        //待审核提现申请
        $tot_m = TechnicianBalance::where(['t_id'=>$t_id,'balance_type'=>3,'status'=>0])->field('abs(change_balance) as change_balance')->select()->toArray();
        $tot_m = array_sum(array_column($tot_m, 'change_balance'));
        //可提现余额
        $withdrawal_money = Price::pricecalc($technician->balance,'-',$tot_m);
        if($withdrawal_money == 0) return show(400,'无可提现金额');
        if(bccomp($money, $withdrawal_money,2) == 1) return show(400,'最多可提现'.$withdrawal_money.'元');

        $res = TechnicianBalance::change($t_id,-$money,3,'提现申请',0,0);
        if($res){
            return show(200,'提交成功');
        }
        return show(400,'提交失败');
    }

}